import axios from 'axios'
import { ElLoading } from 'element-plus'
import router from '@/router/index.js'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const DEFAULT_LOADING = true

class GstyRequest {
  constructor(config) {
    // 1、创建axios 实例
    this.instance = axios.create(config)

    // 2、保存基础配置信息
    this.showLoading = config.showLoading ?? DEFAULT_LOADING

    // 3、实例的拦截器

    this.instance.interceptors.request.use(
      config.interceptors?.requestSuccessFn,
      config.interceptors?.requestFailureFn
    )
    this.instance.interceptors.response.use(
      config.interceptors?.responseSuccessFn,
      config.interceptors.responseFailureFn
    )

    // 4、所有实例-拦截器
    this.instance.interceptors.request.use(
      (config) => {
        NProgress.start()
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: '正在加载~~~~',
            background: 'rgba(0, 0, 0, 0.5)'
          })
        }
        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        // 将loading移除
        NProgress.done()
        this.loading?.close()
        return res.data
      },
      (err) => {
        if (err.response.data.code == '90008') {
          // router.replace(`/login?redirect=${window.location.hash.slice(2)}`)
          router.replace(`/login?redirect=${router.currentRoute.value.name}`)
          // console.log('123',router.currentRoute.value.name)
          router.push('/login')
        }
        // 将loading移除
        NProgress.done()
        this.loading?.close()
        return err
      }
    )
  }

  // 封装网络请求的方法
  request(config) {
    // 1、添加单次请求的拦截器
    if (config.interceptors?.requestSuccessFn) {
      config = config.interceptors.requestSuccessFn(config)
    }

    // 2、判断是否需要显示 loading
    if (config.showLoading === false) {
      this.showLoading = false
    }

    // 返回Promise
    return new Promise((resolve, reject) => {
      this.instance
        .request(config)
        .then((res) => {
          // 3、单个请求对数据的处理
          if (config.interceptors?.responseSuccessFn) {
            res = config.interceptors.responseSuccessFn(res)
          }

          // 4、将showing 设置为默认值，避免影响其他请求
          this.showLoading = DEFAULT_LOADING
          // 5、将结果返回
          resolve(res)
        })
        .catch((err) => {
          reject(err)
          // 4、将showing 设置为默认值，避免影响其他请求
          this.showLoading = DEFAULT_LOADING
        })
    })
  }

  get(config) {
    return this.request({ ...config, method: 'GET' })
  }
  post(config) {
    return this.request({ ...config, method: 'POST' })
  }

  delete(config) {
    return this.request({ ...config, method: 'DELETE' })
  }
  patch(config) {
    return this.request({ ...config, method: 'PATCH' })
  }
  put(config) {
    return this.request({ ...config, method: 'PUT' })
  }
}

export default GstyRequest
